
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

extern char** environ;
const int MAXSIZE = 100;


int f(char** argv)
{
    int ret = execvpe(argv[0],argv,environ);
    if (ret < 0) 
    {
        printf("commend not fund: %s\n", argv[0]);
        return 1;
    };
    return 0;
}

void fun1(char* cmdline)
{
    //对字符串按照空格分开然后放入参数表中
    char*  argv[MAXSIZE];
    int n = strlen(cmdline), i = 0, j = 0;
    int argc = 0;
    for (i = 0; i < n; i++)
    {
        if (cmdline[i] == ' ' || i == n-1)
        {
            int len = i-j+1; //包括\0
            argv[argc] = (char*)malloc(len);
            int k = 0;
            for (k = 0; k < len-1; k++)
            {
                argv[argc][k] = cmdline[j++];
            }
            argv[argc][k] = '\0';
            j = i+1;
            argc++;
        } 
    }
    argv[argc] = NULL;
    pid_t id = fork();
    if (id == 0)
    {
        //子进程去执行程序
        int code = f(argv);  
        exit(code);
    }

   int status; 
    pid_t w = waitpid(id,&status,0);
    if (w > 0)
    {
        if (WIFEXITED(status))
        {
            if (WEXITSTATUS(status) == 0)
            {
                printf("run suncess, exit code: %d\n", WEXITSTATUS(status));
            }
        }
    }
    else if(w < 0)
    {
        printf("等待失败\n");
    }
    for (i = 0; i < argc; i++)
    {
        free(argv[i]);
        argv[i] = NULL;
    }
    
}

int main()
{
    char cmdline[MAXSIZE];
    while(1)
    {
        fgets(cmdline,MAXSIZE,stdin);
        fun1(cmdline);
    }
    return 0;
}
